package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import cn.hutool.core.util.IdcardUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.Arrays;

/**
 * 入住Service业务层处理
 * 
 * @author zzyl
 * @date 2025-02-18
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private ContractMapper contractMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 申请入住
     * @param dto
     */
    @Override
    public void apply(CheckInApplyDto dto) {
        //1.检验老人是否已经入住
        //通过身份证号查询老人
        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo());
        Elder elderDb = elderMapper.selectOne(queryWrapper);
        if (ObjectUtils.isNotEmpty(elderDb)) {
            //老人已经入住
            throw new BaseException("老人已经入住");
        }
        //2.更新床位状态为已入住
        Bed bed = bedMapper.selectBedById(dto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);

        //3.新增或更新老人
        Elder elder = insertOrUpdateElder(dto.getCheckInElderDto(), bed);

        //4.新增合同
        insertContract(dto, elder);

        //5.新增入住记录
        CheckIn checkIn = insertCheckInInfo(dto, elder);

        //6.新增入住配置
        insertCheckInConfig(checkIn.getId(), dto);
    }

    /**
     * 查看申请入住详情
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo detail(Long id) {
        //返回数据
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();

        //1.封装CheckInConfigVo
        CheckIn checkIn = checkInMapper.selectById(id);
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtils.copyProperties(checkIn, checkInConfigVo);
        LambdaQueryWrapper<CheckInConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CheckInConfig::getCheckInId, id);
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(queryWrapper);
        BeanUtils.copyProperties(checkInConfig, checkInConfigVo);

        //2.封装CheckInElderVo
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        //获取老人id
        Long elderId = checkIn.getElderId();
        Elder elder = elderMapper.selectById(elderId);
        BeanUtils.copyProperties(elder, checkInElderVo);
        checkInElderVo.setAge(IdcardUtil.getAgeByIdCard(elder.getIdCardNo()));

        //3.封装List<ElderFamilyVo>
        String remark = checkIn.getRemark();
        List<ElderFamilyVo> elderFamilys = JSONArray.parseArray(remark, ElderFamilyVo.class);

        //4.封装Contract
        LambdaQueryWrapper<Contract> contractWrapper = new LambdaQueryWrapper<>();
        contractWrapper.eq(Contract::getElderId, elderId);
        Contract contract = contractMapper.selectOne(contractWrapper);

        //统一封装返回
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        checkInDetailVo.setContract(contract);
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        checkInDetailVo.setElderFamilyVoList(elderFamilys);

        return checkInDetailVo;
    }

    /**
     * 新增入住配置
     * @param id
     * @param dto
     */
    private void insertCheckInConfig(Long id, CheckInApplyDto dto) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(id);
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 新增入住记录
     * @param dto
     * @param elder
     * @return
     */
    private CheckIn insertCheckInInfo(CheckInApplyDto dto, Elder elder) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setStartDate(dto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(dto.getCheckInConfigDto().getEndDate());
        checkIn.setNursingLevelName(dto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setStatus(0); //已入住
        checkIn.setRemark(JSON.toJSONString(dto.getElderFamilyDtoList()));
        checkInMapper.insert(checkIn);

        return checkIn;
    }

    /**
     * 新增合同
     * @param dto
     * @param elder
     */
    private void insertContract(CheckInApplyDto dto, Elder elder) {
        Contract contract = new Contract();
        BeanUtils.copyProperties(dto.getCheckInContractDto(), contract);
        contract.setElderId(elder.getId());
        String contractNumber = CodeGenerator.generateContractNumber();
        String contractNo = "HT" + contractNumber;
        contract.setContractNumber(contractNo);
        contract.setElderName(elder.getName());
        // 状态、开始时间、结束时间
        // 签约时间小于等于当前时间，合同生效中
        LocalDateTime checkInStartTime = dto.getCheckInConfigDto().getStartDate();
        LocalDateTime checkInEndTime = dto.getCheckInConfigDto().getEndDate();
        Integer status = checkInStartTime.isBefore(LocalDateTime.now()) ? 0 : 1;
        contract.setStartDate(checkInStartTime);
        contract.setEndDate(checkInEndTime);
        contract.setStatus(status);
        contractMapper.insert(contract);
    }

    /**
     * 新增或更新老人
     * @param checkInElderDto
     * @param bed
     * @return
     */
    private Elder insertOrUpdateElder(CheckInElderDto checkInElderDto, Bed bed) {
        Elder elder = new Elder();
        BeanUtils.copyProperties(checkInElderDto, elder);
        elder.setStatus(1);
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());

        //查询老人信息(身份证号、状态不为1)
        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo())
                .eq(Elder::getStatus, 5);
        Elder elderDb = elderMapper.selectOne(queryWrapper);
        if (ObjectUtils.isNotEmpty(elderDb)){
            elder.setId(elderDb.getId()); //将已有的老人id信息封装给elder对象
            //修改
            elderMapper.updateById(elder);
        } else {
            //新增
            elderMapper.insert(elder);
        }

        return elder;
    }
}
